package cn.akira.domain.award.service;

import cn.akira.domain.award.event.SendAwardMessageEvent;
import cn.akira.domain.award.model.aggregate.UserAwardRecordAggregate;
import cn.akira.domain.award.model.entity.TaskEntity;
import cn.akira.domain.award.model.entity.UserAwardRecordEntity;
import cn.akira.domain.award.model.valobj.TaskStateVO;
import cn.akira.domain.award.repository.IAwardRepository;
import cn.akira.types.event.BaseEvent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fjl95
 * @date 2025/6/9
 * @description
 */
@Service
public class AwardService implements IAwardService {


    @Resource
    private IAwardRepository awardRepository;
    @Resource
    private SendAwardMessageEvent sendAwardMessageEvent;

    @Override
    public void saveUserAwardRecord(UserAwardRecordEntity userAwardRecordEntity) {

        //1.构建消息实体对象，用于MQ消息发送
        SendAwardMessageEvent.SendAwardMessage sendAwardMessage = new SendAwardMessageEvent.SendAwardMessage();
        sendAwardMessage.setUserId(userAwardRecordEntity.getUserId());
        sendAwardMessage.setAwardId(userAwardRecordEntity.getAwardId());
        sendAwardMessage.setAwardTitle(userAwardRecordEntity.getAwardTitle());
        BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> sendAwardMessageEventMessage = sendAwardMessageEvent.buildEventMessage(sendAwardMessage);

        //2.构建任务实体对象
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setUserId(userAwardRecordEntity.getUserId());
        taskEntity.setTopic(sendAwardMessageEvent.topic());
        taskEntity.setMessageId(sendAwardMessageEventMessage.getId());
        taskEntity.setMessage(sendAwardMessageEventMessage);
        taskEntity.setState(TaskStateVO.create);

        //3.构建聚合对象
        UserAwardRecordAggregate userAwardRecordAggregate = new UserAwardRecordAggregate();
        userAwardRecordAggregate.setTaskEntity(taskEntity);
        userAwardRecordAggregate.setUserAwardRecordEntity(userAwardRecordEntity);

        //4.存储聚合对象
        awardRepository.saveUserAwardRecourd(userAwardRecordAggregate);

    }
}
